<?php
/**
 * Created by PhpStorm.
 * User: TS
 * Date: 2017/4/4
 * Time: 17:09
 */
namespace core;

class Loader {

    protected static $namespace = [];

    protected static $includes = [];

    protected static $instance = null;

    /**
     * 单例方法
     * @return null|static
     */
    public static function getInstance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new static();
        }
        return self::$instance;
    }

    /**
     * 自动加载类
     * @param $class
     * @return bool
     */
	public static function autoload($class)
	{

	    $uuid = md5($class. 't0');
	    if (isset(self::$includes[$uuid])) return true;

		list($rootNamespace,) = explode('\\', $class);

		if (!empty(self::$namespace) && isset(self::$namespace[$rootNamespace])) {
            $class = str_replace(
                ['\\', $rootNamespace],
                [DIRECTORY_SEPARATOR, self::$namespace[$rootNamespace]],
                $class
            );
        }

        self::$includes[$uuid] = $class ;
		if (file_exists($class . '.php')) include $class . '.php';
	}

    /**
     * 注册自动加载机制
     * @param string $autoload
     */
    public static function register($autoload = '')
    {
        // 注册系统自动加载
        spl_autoload_register($autoload ?: 'core\\Loader::autoload', true, true);
        self::addNamespace([
            'core' => ROOT_PATH . 'system/core',
            'other' => ROOT_PATH . 'other',
            'apps' => ROOT_PATH . 'apps',
        ]);
    }

    /**
     * 添加命名空间
     * @param $namespace
     * @param $path
     */
    public static function addNamespace($namespace, $path = '')
    {
        if (is_array($namespace)) foreach ($namespace as $k => $v) {
            self::$namespace[$k] = $v;
        } else {
            self::$namespace[$namespace] = $path;
        }
    }

}